#!/usr/bin/env bash

# 判断容器是否启动成功
function rocketmq_successOrNot() {
  echo_sleep "docker run命令:\n $dockerRunCmd \n" 2
  if [[ -n $(docker ps -q -f "name=^$application$") ]]; then
    echo_red "$application 容器启动成功"
    echo -e "\t端口号：$port"
    echo -e "\t版本号：$version"
    echo -e "\t容器名称：$application"
    echo -e "\t本地映射路径：$applicationPath"
    echo -e "进入容器使用命令：docker exec -it $application /bin/bash"
  else
    log_error "$application 容器启动失败,请检查docker run命令是否有误,端口是否被占用"
  fi
}
# rocketmq_broker配置文件
function rocketmq_broker_config() {
  echo_sleep "开始写入配置文件……"

  cat >${applicationPath}/conf/broker.conf <<-EOF
#所属集群名称，如果节点较多可以配置多个
brokerClusterName = DefaultCluster
#broker名称，master和slave使用相同的名称，表明他们的主从关系
brokerName = broker-a
#0表示Master，大于0表示不同的slave
brokerId = 0
#表示几点做消息删除动作，默认是凌晨4点
deleteWhen = 04
#在磁盘上保留消息的时长，单位是小时
fileReservedTime = 48
#有三个值：SYNC_MASTER，ASYNC_MASTER，SLAVE；同步和异步表示Master和Slave之间同步数据的机制；
brokerRole = ASYNC_MASTER
#刷盘策略，取值为：ASYNC_FLUSH，SYNC_FLUSH表示同步刷盘和异步刷盘；SYNC_FLUSH消息写入磁盘后才返回成功状态，ASYNC_FLUSH不需要；
flushDiskType = ASYNC_FLUSH
#设置broker节点所在服务器的ip地址
brokerIP1 = ${brokerIp}
#磁盘使用达到95%之后,生产者再写入消息会报错 CODE: 14 DESC: service not available now, maybe disk f
diskMaxUsedSpaceRatio=95

EOF

  echo_sleep "配置文件写入完成！\n"

}

# 安装 Rocketmq_rmqnamesrv
docker_rocketmq_rmqnamesrv() {

  application="rmqnamesrv"                       #应用名称,docker ps中显示的名称
  image="rocketmqinc/rocketmq"                   #docker仓库中镜像名称
  applicationPath="/opt/rocketmq/${application}" # 本地映射文件路径
  port="9876"                                    #对外映射的端口号
  version="4.4.0"                                # 镜像版本号,默认为最新版本
  dockerRunCmd=""                                # 最后执行的docker run命令

  echo -e "=========================开始安装rocketmq-namesrv========================="

  echo_yellow "1.检测是否存在 ${application} 容器"
  docker_delExisting ${application}

  echo_yellow "2.开始拉取镜像文件"
  echo -e "如:4.4.0 4.3.0 4.2.0"
  docker_pull

  echo_yellow "3.开始创建本地映射目录"
  create_file_path store logs

  echo_yellow "4.创建并启动docker容器"
  port=$(read_input "请输入需要映射的端口(默认为 ${port})：" ${port})
  application=$(read_input "请输入容器的名称(默认为 ${application})：" ${application})

  echo -e "${application}启动中,请等待......"

  dockerRunCmd="docker run --restart=always --privileged=true \
	--name $application \
	-p $port:9876 \
	-v $applicationPath/logs:/root/logs \
	-v $applicationPath/store:/root/store \
	-e \"MAX_POSSIBLE_HEAP=100000000\" \
	-d $image:$version sh mqnamesrv	&> /dev/null"

  eval $dockerRunCmd

  echo_yellow "6.检测容器是否启动成功"
  rocketmq_successOrNot

  echo -e "\n=========================安装rocketmq-namesrv结束========================="
}

# 安装Rocketmq_broker
docker_rocketmq_broker() {

  application="rmqbroker"                        # 应用名称,docker ps中显示的名称
  image="rocketmqinc/rocketmq"                   # docker仓库中镜像名称
  applicationPath="/opt/rocketmq/${application}" # 本地映射文件路径
  port="9876"                                    # 对外映射的端口号
  version="4.4.0"                                # 镜像版本号,默认为最新版本
  dockerRunCmd=""                                # 最后执行的docker run命令
  local port="10911"
  local port1="10909"
  local namesrvProt="9876"
  local brokerIp=""

  echo -e "===========安装rocketmq-broker开始==========="

  echo_yellow "1.检测是否存在 ${application} 容器"
  docker_delExisting ${application}

  echo_yellow "2.开始拉取镜像文件"
  echo -e "如:4.4.0 4.3.0 4.2.0 "
  docker_pull

  echo_yellow "3.开始创建本地映射目录"
  create_file_path store logs conf

  echo_yellow "4.创建并启动docker容器"
  application=$(read_input "请输入容器的名称(默认为 ${application})：" ${application})
  namesrvProt=$(read_input "请输入namesrv端口号(默认为 9876)：" ${namesrvProt})
  port=$(read_input "需要映射到非vip通道的端口(默认为 ${port})：" ${port})
  port1=$(read_input "需要映射到vip通道的端口(默认为 ${port1})：" ${port1})

  echo "本机IP地址如下(如有多网卡ip可能会不准确,请自行确认)"
  hostname -I | awk '{print $1}'
  brokerIp=$(read_input "请输入broker节点所在服务器的ip地址：" ${brokerIp})

  echo_yellow "5.开始创建配置文件"
  rocketmq_broker_config

  echo -e "${application}启动中,请等待......"

  dockerRunCmd="docker run -d  \
		--restart=always \
		--name $application \
		--link rmqnamesrv:namesrv \
		-p $port:10911 \
		-p $port1:10909 \
		-v  ${applicationPath}/logs:/root/logs \
		-v  ${applicationPath}/store:/root/store \
		-v ${applicationPath}/conf/broker.conf:/opt/rocketmq-4.4.0/conf/broker.conf \
		-e "NAMESRV_ADDR=namesrv:${namesrvProt}" \
		-e "MAX_POSSIBLE_HEAP=200000000" \
		${image}:$version \
		sh mqbroker -c /opt/rocketmq-4.4.0/conf/broker.conf &> /dev/null"

  eval $dockerRunCmd

  echo_yellow "6.检测容器是否启动成功"
  rocketmq_successOrNot

  echo -e "\n===========安装rocketmq-broker结束==========="
}

# 安装 Rocketmq_console
docker_rocketmq_console() {
  application="rmqConsole"                       # 应用名称,docker ps中显示的名称
  image="pangliang/rocketmq-console-ng"          # docker仓库中镜像名称
  applicationPath="/opt/rocketmq/${application}" # 本地映射文件路径
  port="8080"                                    # 对外映射的端口号
  version="latest"                               # 镜像版本号,默认为最新版本
  dockerRunCmd=""                                # 最后执行的docker run命令

  local namesrv=""

  echo -e "===========安装rocketmq-console开始==========="

  echo_yellow "1.检测是否存在 ${application} 容器"
  docker_delExisting ${application}

  echo_yellow "2.开始拉取镜像文件"
  docker pull $image:$version

  echo_yellow "3.开始创建本地映射目录"
  create_file_path store logs

  echo_yellow "4.创建并启动docker容器"
  port=$(read_input "请输入需要映射的端口(默认为 ${port})：" ${port})
  application=$(read_input "请输入容器的名称(默认为 ${application})：" ${application})
  namesrv=$(read_input "请输入namesrv服务的ip地址及端口号(例:127.0.0.1:8080)：" ${namesrv})

  echo -e "${application}启动中,请等待......"

  echo -e "开始创建并启动容器……\n"
  dockerRunCmd="docker run -d \
		--restart=always \
		--name ${application} \
		-e \"JAVA_OPTS=-Drocketmq.namesrv.addr=$namesrv -Dcom.rocketmq.sendMessageWithVIPChannel=false\" \
		-p $port:8080 \
		pangliang/rocketmq-console-ng &> /dev/null"

  eval $dockerRunCmd

  echo_yellow "5.检测容器是否启动成功"
  rocketmq_successOrNot

  echo -e "\n===========安装rocketmq-console结束==========="
}

rocketmq_install() {
  echo -e "\n============RockerMq一键部署============\n"
  echo -e "(1) 安装 namesrv \n"
  echo -e "(2) 安装 broker \n"
  echo -e "(3) 安装 rocketmq-console \n"
  #echo -e "(4) 安装全部服务 namesrv broker rocketmq-console \n"
  echo -e "(99) 返回上一层"
  echo -e "\n============RockerMq一键部署============\n"
  read -r -p "请输入要安装服务的编号：" input

  case $input in
  1)
    docker_rocketmq_rmqnamesrv
    ;;
  2)
    docker_rocketmq_broker
    ;;
  3)
    docker_rocketmq_console
    ;;
  4)
    docker_rocketmq_rmqnamesrv
    docker_rocketmq_broker $port
    docker_rocketmq_console
    ;;
  99)
    echo -e "返回上一层"
    ;;
  *)
    echo "编号输入错误,请重新输入!"
    ;;
  esac
}
